package com.dm.service.impl;

import com.dm.service.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Author DongJunJun
 * @Date 2022/9/6 19:06
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 发件人
     */
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.nikeName}")
    private String nikeName;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(nikeName+"<"+from+">");
        //发送
        javaMailSender.send(simpleMailMessage);
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(from);
        //抄送的人
        simpleMailMessage.setCc(cc);
        //发送
        javaMailSender.send(simpleMailMessage);
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String path) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);
            File file = new File(path);
            FileSystemResource fileSystemResource = new FileSystemResource(file);
            String fileName = file.getName();
            //添加附件
            mimeMessageHelper.addAttachment(fileName,fileSystemResource);
            //发送
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }
}
